package org.example.mq.mqserver.core;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.example.mq.common.exception.MqException;

import java.io.Serial;
import java.io.Serializable;
import java.util.UUID;

@Data
@Slf4j
public class Message implements Serializable {
    //消息版本 用于更改后判断序列化是否出错
    @Serial
    private static final long serialVersionUID = 1L;

    private BasicProperties basicProperties = new BasicProperties();
    private byte[] body;

    //消息保存在文件中,记录在文件中的位置
    private transient long offsetBeg = 0;     //消息数据开头距离文件开头的位置偏移
    private transient long offsetEnd = 0;     //消息数据结尾距离文件开头的位置偏移

    //表示消息是否有效
    private byte isValid = 0x1;

    public String getMessageId(){
        return basicProperties.getMessageId();
    }

//    private void setMessageId(){
//        basicProperties.setMessageId("M-" + UUID.randomUUID());
//    }

    public String getRoutingKey(){
        return basicProperties.getRoutingKey();
    }

    public boolean setRoutingKey(String routingKey){
        try{
            basicProperties.setRoutingKey(routingKey);
            return true;
        }catch (Exception e){
            log.error("Message.setRoutingKey,设置失败",e);
            return false;
        }
    }

    //创建工厂方法，让这个方法来进行实例化
    //这个方法会自动生成一个uuid
    public static Message createMessageWithID(BasicProperties properties,String RoutingKey,byte[] body){
        Message message = new Message();

        validate(RoutingKey,properties,body);

        if(properties==null) {
            message.basicProperties.setMessageId("M-"+UUID.randomUUID());
            message.setRoutingKey(RoutingKey);
        }
        else message.setBasicProperties(properties);
        message.setBody(body);

        return message;
    }


    //参数校验
    private static void validate(String routingKey, BasicProperties properties, byte[] body) {
//        if (routingKey == null || routingKey.isBlank()) {
//            throw new IllegalArgumentException("routingKey must not be null or blank");
//        }
        if(routingKey == null){
            throw new MqException("[Message:validate]routingKey不能为null");
        }
        if (body == null || body.length == 0) {
            throw new IllegalArgumentException("body must not be null or empty");
        }
    }

    //设置无效
    public void setInvalid(){
        isValid = 0x0;
    }

    //判断是否有效
    public boolean msgIsAlive(){
        return isValid == 0x1;
    }

    //消息是否持久化
    public boolean isDelivery(){
        return basicProperties.getDeliverMode() == 2;
    }

}
